
//
//  WBHomeViewController.swift
//  SinaWebo
//
//  Created by 亚杏 on 2017/5/5.
//  Copyright © 2017年 oms. All rights reserved.
//

import UIKit

//定义全局常量
private let originalCellID = "originalCellID"
private let retweetedCellID = "retweetedCellID"

class WBHomeViewController: WBBaseViewController {

    //微博列表模型数组
    private lazy var listViewModel = WBStatusListViewModel()


    override func viewDidLoad() {
        super.viewDidLoad()
        
        //注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(bowserPhoto), name: NSNotification.Name(rawValue: WBStatusCellBrowserPhotoNotification), object: nil)
        
        
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc private func bowserPhoto(n: Notification) {
        //1.从通知的 userinfo传递参数
      guard let selectedIndex = n.userInfo?[WBStatusCellBrowserPhotoSelectedIndexKey] as? Int,
            let urls = n.userInfo?[WBStatusCellBrowserPhotoURLsKey] as? [String],
            let imageViewList = n.userInfo?[WBStatusCellBrowserPhotoImageViewsKey] as? [UIImageView]
        else{
            return
        }
        
        let vc = HMPhotoBrowserController.photoBrowser(withSelectedIndex: selectedIndex, urls: urls, parentImageViews: imageViewList)
        present(vc, animated: true, completion: nil)
        
    }
    
    
    //重写父类方法
    override func setupTableView() {
        super.setupTableView()

        navItem.leftBarButtonItem = UIBarButtonItem(title: "好友", target: self, action: #selector(showFriends))

        //注册cell
        tableView?.register(UINib(nibName: "WBStatusNormalCell", bundle: nil), forCellReuseIdentifier: originalCellID)
        tableView?.register(UINib(nibName: "WBStatusRetweetedCell", bundle: nil), forCellReuseIdentifier: retweetedCellID)
        
//        tableView?.rowHeight = UITableViewAutomaticDimension
        tableView?.estimatedRowHeight = 300
        tableView?.separatorStyle = .none
        setupNavTitle()

        loadData()

    }
    
    //设置导航栏标题
    private func setupNavTitle(){
        let title = WBNetworkManager.shared.userAccount.screen_name
        
        let btn = WBTitleButton(title: title)
        btn.addTarget(self, action: #selector(clickTitleBtn), for: .touchUpInside)
        
        
        navItem.titleView = btn
        
    }
    
    @objc func clickTitleBtn(btn: UIButton){
        btn.isSelected = !btn.isSelected
        
    }
    


    override func loadData() {

        //xcode8控件刷新有问题，不能显示小菊花
        refreshControl?.beginRefreshing()
        
        //模拟延时加载数据
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
            self.listViewModel.loadStatus(pullup: self.isPullup) {(isSuccess,shouldRefresh) in

                print("加载数据结束")
                //结束刷新
                self.refreshControl?.endRefreshing()
                //恢复上拉刷新标记
                self.isPullup = false

                if shouldRefresh{
                    self.tableView?.reloadData()
                }

            }
            //用网络工具加载数据
            WBNetworkManager.shared.statusList { (list:[[String : AnyObject]]?, isSuccess: Bool) in
                //            print(list ?? "")
            }

        }


    }


    //显示好友
    @objc private func showFriends(){
        print("点击显示好友")
        let demoVC = WBDemoViewController()
        navigationController?.pushViewController(demoVC, animated: true)
    }

//MARK:表格数据源方法
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return listViewModel.statusList.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //0,取出视图模型，根据视图模型判断可重用cell
        let viewModel = listViewModel.statusList[indexPath.row]
        let cellID = (viewModel.status.retweeted_status != nil) ? retweetedCellID : originalCellID

        //1.取cell
        let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! WBStatusCell

        //2.设置cell
        cell.viewModel = viewModel

        // 设置代理 
        // 如果用 block 需要在数据源方法中，给每个cell设置block
        // 如用代理 ，只需要传递一个指针
        cell.delegate = self
      
        //3.返回cell
        return cell
    }

    //父类必须实现代理方法，子类才能重写
   override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let vm = listViewModel.statusList[indexPath.row]

        return vm.rowHeight
    }



}

//MARK: - WBStatusCellDelegate
extension WBHomeViewController: WBStatusCellDelegate {

    func statusCellDidSelectedURLStr(cell: WBStatusCell, urlStr: String) {
        print(urlStr)
        let vc = WBWebViewController()
        vc.urlStr = urlStr
        navigationController?.pushViewController(vc, animated: true)
    }
}

